﻿using Spire.Pdf;
using System.Drawing;
using System.Text;

namespace DocMark
{
    internal class PdfHandler : IMarkLister
    {
        private const string _partName = "temp_{0}.pdf";

        public event Action<string>? HandleMsg;

        public async Task<List<string>> GetTextAsync(string filePath, Color textColor)
        {
            using var stream = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite);
            return await GetTextAsync(stream, textColor);
        }

        public async Task<List<string>> GetTextAsync(Stream stream, Color textColor)
        {
            int count = await Task.Run(() =>
            {
                PdfDocument document = new(stream);
                int count = document.Pages.Count;
                foreach (PdfPageBase page in document.Pages)
                {
                    for (int i = 0; i < page.ImagesInfo.Length; i++)
                        page.DeleteImage(i);
                }
                document.Split(FileTool.GetFilePath(_partName));
                document.Close();
                document.Dispose();
                return count;
            });

            List<string> texts = new();
            List<Task<List<string>>> tasks = new();

            WordHandler wordHandler = new();

            for (int i = 0; i < count; i++)
            {
                string path = FileTool.GetFilePath(string.Format(_partName, i));
                PdfDocument pdfDocument = new(path);
                File.Delete(path);
                using MemoryStream docxStream = new();
                docxStream.Position = 0;
                pdfDocument.SaveToStream(docxStream, FileFormat.DOCX);
                pdfDocument.Close();
                docxStream.Position = 0;
                var strs = await wordHandler.GetTextAsync(docxStream, Color.FromArgb(255, 255, 48, 0));
                texts.AddRange(strs);
            }
            return texts;
        }


        public async Task<bool> MarkAsync(string filePath, string saveFilePath, List<string> markText, Color textColor)
        {
            throw new NotImplementedException();
        }
    }
}
